package master.quantumComputerIO.network;

import java.awt.FileDialog;
import java.io.*;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import master.*;

/**
 * Class provides functionality for saving serialisable quantum network object instances
 * as loadable files
 * @author Luke Dobinson
 *
 */

public class QuantumNetworkIO {
	public static QuantumNetwork readNetwork(String filename) throws QuantumNetworkException{
		try{
			FileInputStream fis = new FileInputStream(filename);
			ObjectInputStream ois = new ObjectInputStream(fis);
			
			Object net = ois.readObject();
			
			ois.close();
			fis.close();
			
			if(net instanceof QuantumNetwork)
				return (QuantumNetwork)net;
			else
				throw new QuantumNetworkException("Object not a Quantum network");
			
			
		}catch(IOException e){
			throw new QuantumNetworkException("");
		} catch (ClassNotFoundException e) {
			throw new QuantumNetworkException("");
		}
		
	}
	
	public static void writeNetwork(QuantumNetwork net, String filename)throws QuantumNetworkException{
		try{
			FileOutputStream fos = new FileOutputStream(filename);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(net);
			oos.close();
			fos.close();
		}catch(IOException e){
			throw new QuantumNetworkException("");
		}
	}
	
	public static QuantumNetwork loadDialog() throws QuantumNetworkException{
		FileDialog myDialog = new FileDialog(new JFrame());
		myDialog.setMode(FileDialog.LOAD);
		
		myDialog.setVisible(true);
		String dir = myDialog.getDirectory();
		String filename = myDialog.getFile();
		if(filename == null) throw new QuantumNetworkException("no network selected");
		
		try{
			return readNetwork(dir+filename);
		}catch(QuantumNetworkException e){
			JOptionPane.showMessageDialog(null, "Error, network not loaded");
			throw e;
		}
		
	}
	public static void saveDialog(QuantumNetwork n) throws QuantumNetworkException{
		FileDialog myDialog = new FileDialog(new JFrame());
		myDialog.setMode(FileDialog.SAVE);
		
		myDialog.setVisible(true);
		String dir = myDialog.getDirectory();
		String filename = myDialog.getFile();
		if(filename == null) throw new QuantumNetworkException("no register selected");
		try{
			writeNetwork(n,dir+filename);
		}catch(QuantumNetworkException e){
			JOptionPane.showMessageDialog(null, "Error, network not saved");
			throw e;
		}
	}
}
